package admin

import (
	"context"
	"fmt"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/admin/adminLogic"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/businessCommonQuery"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
)

func (rpc *admin) AdminDetail(ctx context.Context, pb *pbAdmin.AdminDetailReq) (*pbAdmin.AdminDetailResp, error) {
	adminIds := []interface{}{}
	authRuleIds := []interface{}{}
	if pb.OperaterId != 0 {
		adminIds = adminLogic.GetChildrenRoleAdminIds(ctx, pb.OperaterId, true)
		authRuleIds = adminLogic.GetRoleIdsByAdminId(ctx, pb.OperaterId)
	} else {
		adminIds = append(adminIds, pb.OperaterId)
	}

	if pb.Id == 0 {
		return nil, businessError.ErrorInfoToRpcError(businessError.ParamsInvalid)
	}

	Db := database.Db.GetDefaultDb(ctx)
	row, dbErr := Db.Find("select * from admin where id=? and id in (?)", pb.Id, adminIds)

	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	if row == nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.NotFound)
	}

	businessCommonQuery.ListFormat(adminLogic.List(), row)

	roles, dbErr := Db.Query("select a.admin_id,g.* from admin_role_access a "+
		"join admin_role g on g.id=a.role_id "+
		"where admin_id in (?)", pb.Id)

	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	ids := []string{}
	names := []string{}
	ids2 := []interface{}{}
	for _, role := range roles {
		ids = append(ids, fmt.Sprintf("%v", role["id"]))
		ids2 = append(ids2, role["id"])
		names = append(names, fmt.Sprintf("%v", role["name"]))
	}

	row["disabled"] = 0
	row["role_id"] = utils.Implode(",", ids)
	row["role_text"] = utils.Implode(",", names)
	if len(utils.ArrayIntersect(ids2, authRuleIds)) > 0 {
		row["disabled"] = 1
	}

	return &pbAdmin.AdminDetailResp{
		Row: &pbAdmin.Admin{
			Id:              row["id"].(int64),
			Email:           row["email"].(string),
			Username:        row["username"].(string),
			Nickname:        row["nickname"].(string),
			Password:        row["password"].(string),
			Salt:            row["salt"].(string),
			Avatar:          row["avatar"].(string),
			Loginfailure:    int32(row["loginfailure"].(int64)),
			Token:           row["token"].(string),
			TokenExpiryTime: row["token_expiry_time"].(string),
			Status:          int32(row["status"].(int64)),
			LoginTime:       row["login_time"].(string),
			CreateTime:      row["create_time"].(string),
			UpdateTime:      row["update_time"].(string),
			StatusText:      row["status_text"].(string),
			RoleId:          row["role_id"].(string),
			RoleText:        row["role_text"].(string),
			Disabled:        int32(row["disabled"].(int)),
		},
	}, nil
}
